<template>
  <div class="manage">
    <!-- 弹窗功能 -->
    <el-dialog
      :title="this.modalType ? '编辑' : '新增'"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <!-- 用户的表单信息 -->
      <el-form
        ref="form"
        :inline="true"
        :model="form"
        label-width="80px"
        :rules="rules"
      >
        <!-- rules和下面的prop属性都是用来做表单校验的 -->
        <el-form-item label="姓名" prop="name">
          <!-- 在编辑状态下禁用当前input，disabled的值必须显示转换成布尔类型 -->
          <el-input
            placeholder="请输入姓名"
            v-model="form.name"
            :disabled="Boolean(this.modalType)"
          ></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input placeholder="请输入年龄" v-model="form.age"></el-input>
        </el-form-item>

        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择性别">
            <el-option label="男" :value="1"></el-option>
            <el-option label="女" :value="0"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="出生日期" prop="birth">
          <el-date-picker
            v-model="form.birth"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="地址" prop="addr">
          <el-input placeholder="请输入地址" v-model="form.addr"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 新增按钮 -->
    <div class="manage-header">
      <el-button type="primary" @click="addFn"> + 新增 </el-button>
      <el-button type="primary" @click="chooseAll"> √ 全选 </el-button>

      <!-- form搜索区域 -->
      <el-form :model="userForm" :inline="true">
        <el-form-item>
          <el-input placeholder="请输入姓名" v-model="userForm.name"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchUserFn">查询</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格 -->
    <el-table
      :data="tableData"
      v-loading="tableLoad"
      element-loading-text="加载中"
      style="width: 100%; margin-top: 20px"
      stripe
      border
      height="90%"
      @selection-change="handleSelectionChange"
      :row-key="getRowKey"
      ref="multipleTable"
    >
      <el-table-column
        type="selection"
        width="55"
        :reserve-selection="true"
        id="checkBtn"
      >
      </el-table-column>
      <el-table-column label="姓名" prop="name"></el-table-column>
      <el-table-column label="性别" prop="sex">
        <!-- <template slot-scope="scope">
          <span>{{scope.row.sex?'男':'女'}}</span>
        </template> -->

        <template #default="{ row }">
          <span>{{ row.sex ? "男" : "女" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="年龄" prop="age"></el-table-column>
      <el-table-column label="出生日期" prop="birth"></el-table-column>
      <el-table-column label="地址" prop="addr"></el-table-column>

      <!-- 处理按钮 -->
      <el-table-column>
        <template #default="scope">
          <!-- scope是一个对象，其中一个属性时"$index" -->
          <el-button
            size="mini"
            @click="handleEdit(scope.$index, scope.row, scope)"
            >编辑</el-button
          >
          <el-button size="mini" @click="handleDelete(scope.row)" type="danger"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <div>
      <el-pagination
        layout="prev, pager, next"
        :total="total"
        @current-change="handlePage"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { getUser, addUser, editUser, delUser } from '../api/index.js'
export default {
  data () {
    return {
      dialogVisible: false,
      form: {
        name: '',
        age: '',
        sex: '',
        birth: '',
        addr: ''
      },
      rules: {
        name: [{ required: true, message: '请输入姓名' }],
        age: [{ required: true, message: '请输入年龄' }],
        sex: [{ required: true, message: '请输入性别' }],
        birth: [{ required: true, message: '请输入出生日期' }],
        addr: [{ required: true, message: '请输入地址' }]
      },
      tableData: [], // 表格数据，注意默认数据类型为array
      modalType: 0, // 0表示弹框为添加，1表示弹框为修改
      total: 0, // 当前的总条数

      /**
       * 这个pageData是前端定义的，
       * 用于分页时传递的参数，
       *
       */
      pageData: {
        page: 1,
        limit: 6
      },

      // 根据名字来进行查找
      userForm: {
        name: ''
      },

      // 表格加载
      tableLoad: false,

      // 记录选择数据
      multipleSelection: []
    }
  },
  methods: {
    // 表单提交事件
    submit () {
      this.$refs.form.validate(async (valid) => {
        // 当表单校验规则通过之后，值为true
        // console.log(valid)

        if (valid) {
          if (this.modalType === 0) {
            // 0是添加
            const res = await addUser(this.form)
            console.log(res)
          } else {
            // 1是编辑
            const res = await editUser(this.form)
            console.log(res)
          }
          this.handleClose()

          // 更新表格数据
          this.getUserFn()

          // 关闭弹窗
          this.dialogVisible = false
        }
      })
    },

    // 表单取消事件
    cancel () {
      this.dialogVisible = false
      this.handleClose()
    },

    // 表单重置事件
    handleClose () {
      // console.log(this.$refs.form)
      this.$refs.form.resetFields()
      this.dialogVisible = false
    },

    // 获取用户列表
    async getUserFn (isAll = false) {
      // const res = await getUser({
      //   params: { ...this.userForm, ...this.pageData }
      // })
      // this.tableData = res.list
      // this.total = res.count || 0
      getUser({ params: { ...this.userForm, ...this.pageData } }).then(
        (res) => {
          this.tableData = res.list
          this.total = res.count || 0

          if (isAll) {
            // 注意这个函数写在回调里面
            // nextTick是异步函数，等同步代码执行完毕后，看异步队列中哪个代码快执行哪个。
            this.$nextTick(() => {
              document
                .getElementsByTagName('thead')[0]
                .firstChild.firstChild.firstChild.firstChild.click()
            })
          }
        }
      )
    },

    // 编辑
    async handleEdit (index, row, scope) {
      console.log(index)
      console.log(scope)
      this.dialogVisible = true
      this.modalType = 1

      // 注意这里不可以直接相等，要使用深拷贝，防止点击取消或者关闭时出错误
      // this.form = row
      this.form = JSON.parse(JSON.stringify(row))
    },

    // 删除
    handleDelete (row) {
      console.log(row)
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const res = await delUser(row)
          // console.log(res.code)
          if (res.code === 20000) {
            this.getUserFn()
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },

    // 添加
    addFn () {
      this.dialogVisible = true
      this.modalType = 0
    },

    /** 选择页码的回调函数 */
    handlePage (val) {
      this.pageData.page = Number(val)
      this.getUserFn()
    },

    /** 查找方法 */
    searchUserFn () {
      this.getUserFn()
    },

    toggleSelection (rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.multipleTable.toggleRowSelection(row)
        })
      } else {
        this.$refs.multipleTable.clearSelection()
      }
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
      console.log(val)
    },
    chooseAll () {
      this.pageData.limit = this.total
      this.getUserFn(true)
    },
    getRowKey (row) {
      return row.id
    }
  },
  created () {
    this.getUserFn()
    console.log('user页面接口被调用')
  }
}
</script>

<style lang="less" scoped>
.manage {
  height: 90%;
  .manage-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
</style>
